package com.da.auth.service.impl;

import com.da.common.entity.PageResult;
import com.da.common.enums.ResultEnum;
import com.da.common.exception.BusinessException;
import com.da.common.exception.ParameterException;
import com.da.common.utils.SnowflakeIdWorker;
import com.da.common.utils.TimestampUtil;
import com.da.auth.convert.DailyRoleConverter;
import com.da.auth.entity.DailyRole;
import com.da.auth.entity.DailyRolePermissions;
import com.da.auth.entity.dto.DailyRoleDTO;
import com.da.auth.mapper.CommonMapper;
import com.da.auth.mapper.DailyRoleMapper;
import com.da.auth.mapper.DailyRolePermissionsMapper;
import com.da.auth.service.DailyRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Optional;


/**
 * 角色表(DailyRole)表服务实现类
 *
 * @author hyacinth
 * @since 2025-01-20 14:49:21
 */
@Service
@Slf4j
public class DailyRoleServiceImpl implements DailyRoleService {

    private final DailyRoleMapper dailyRoleMapper;

    private final CommonMapper<?> commonMapper;

    private final DailyRolePermissionsMapper dailyRolePermissionsMapper;

    public DailyRoleServiceImpl(DailyRoleMapper dailyRoleMapper, CommonMapper<?> commonMapper,
                                DailyRolePermissionsMapper dailyRolePermissionsMapper) {
        this.dailyRoleMapper = dailyRoleMapper;
        this.commonMapper = commonMapper;
        this.dailyRolePermissionsMapper = dailyRolePermissionsMapper;
    }

    /**
     * 新增角色
     *
     * @param dailyRoleDTO 角色信息
     * @return
     */
    @Override
    public Boolean createRole(DailyRoleDTO dailyRoleDTO) {
        DailyRole dailyRole = DailyRoleConverter.INSTANCE.convertToEntity(dailyRoleDTO);

        Optional.ofNullable(dailyRoleDTO.getRoleName())
                .orElseThrow(() -> new ParameterException(ResultEnum.FAIL.getCode(), "角色名称不能为空！"));

        int count = commonMapper.queryCountByCondition("daily_role", "role_name", dailyRoleDTO.getRoleName());
        if (count > 0) {
            log.error("该角色已存在，请勿重复添加");
            throw new BusinessException(ResultEnum.FAIL.getCode(), "该角色已存在，请勿重复添加");
        }

        dailyRole.setId(String.valueOf(SnowflakeIdWorker.generateId()));
        dailyRole.setCreatedAt(TimestampUtil.now());
        // 关联角色权限
        DailyRolePermissions dailyRolePermissions = new DailyRolePermissions();
        dailyRolePermissions.setRoleId(dailyRole.getId());
        dailyRolePermissions.setId(String.valueOf(SnowflakeIdWorker.generateId()));
        dailyRolePermissions.setPermissionId(dailyRoleDTO.getPermissionId());
        try {
            int isCreateRole = dailyRoleMapper.createRole(dailyRole);

            return isCreateRole > 0;
        } catch (Exception e) {
            log.error("新增角色失败:{}", e.getMessage());
            throw new BusinessException(ResultEnum.FAIL.getCode(), e.getMessage());
        }
    }

    /**
     * 分页查询所有角儿
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<DailyRole> queryPageAllRole(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<DailyRole> dailyRoles = dailyRoleMapper.queryPage(offset, pageSize);
        long total = dailyRoleMapper.selectCount();
        return new PageResult<>(pageNum, pageSize, total, dailyRoles);
    }

    @Override
    public DailyRole queryRoleInfoById(String id) {
        return dailyRoleMapper.selectById(id);
    }


    /**
     * 修改角色信息
     *
     * @param dailyRole
     * @return
     */
    @Override
    public Boolean updateRole(DailyRole dailyRole) {
        String id = dailyRole.getId();
        Optional.ofNullable(id).orElseThrow(() -> new ParameterException(ResultEnum.FAIL.getCode(), "角色id不能为空!"));
        DailyRole data = (DailyRole) commonMapper.queryDataById("daily_role", id);
        if (ObjectUtils.isEmpty(data)) {
            log.error("未查询到该id为:" + id + "的用户信息");
            throw new BusinessException(ResultEnum.FAIL.getCode(), "未找到 ID 为 " + id + " 的角色");
        }
        try {
            dailyRole.setUpdatedAt(TimestampUtil.now());
            int isUpdateRole = dailyRoleMapper.updateById(dailyRole);
            return isUpdateRole > 0;
        } catch (Exception e) {
            log.error("修改用户信息异常:{}", e.getMessage());
            throw new BusinessException(ResultEnum.FAIL.getCode(), e.getMessage());
        }
    }

    /**
     * 删除角色
     *
     * @param id
     * @return
     */
    @Override
    public Boolean deletedRole(String id) {
        DailyRole data = (DailyRole) commonMapper.queryDataById("daily_role", id);
        if (ObjectUtils.isEmpty(data)) {
            log.error("未查询到该id为:" + id + "的用户信息");
            throw new BusinessException(ResultEnum.FAIL.getCode(), "未找到 ID 为 " + id + " 的角色");
        }

        try {
            Integer count = dailyRolePermissionsMapper.queryByRoleId(id);
            if (count > 0){
                dailyRolePermissionsMapper.deletedByUserId(id);
            }
            int isDeletedRole = dailyRoleMapper.deleteById(id);
            return isDeletedRole > 0;
        } catch (Exception e) {
            log.error("删除角色失败:{}", e.getMessage());
            throw new BusinessException(ResultEnum.FAIL.getCode(), e.getMessage());
        }
    }

    /**
     * 批量删除角色
     *
     * @param roleIdList
     * @return
     */
    @Override
    public Boolean batchDeletedRole(List<String> roleIdList) {
        try {
            int deletedCount = dailyRoleMapper.deleteBatchIds(roleIdList);
            log.info("批量删除角色成功，删除数量: {}", deletedCount);
            return deletedCount > 0;
        } catch (Exception e) {
            log.error("批量删除角色失败: {}", e.getMessage(), e);
            throw new BusinessException(ResultEnum.FAIL.getCode(), "批量删除角色失败: " + e.getMessage());
        }
    }
}
